<?php
class Json {
	
	private function _encode($dict) {
		$result = array();
		$json = "{";
		foreach ($dict as $key => $value) {
			if (is_array($value)) {
				$result[] = sprintf('"%s":%s', $key, $this->_encode($value));
			} else if (is_object($value)) {
				$value   = (array) get_class_vars(get_class($value));
				$result[] = sprintf('"%s":%s', $key, $this->_encode($value));
			} else {
				$result[] = sprintf('"%s":"%s"', $key, $this->_escapeString($value));
			}
		}
		$json .= implode(",", $result);
		$json .= "}";
		return $json;
	}
	
	private function _escapeString($string) {
		$search  = array('\\', "\n", "\t", "\r", "\b", "\f", '"', "'");
		$replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\"', "\'");
        $string  = str_replace($search, $replace, $string);
        $string  = str_replace(array(chr(0x08), chr(0x0C)), array('\b', '\f'), $string);
        return (string) $string;
	}

	public function decode($json) { # needs more thinking
		$comment = false;
		$out = '$x=';
		for ($i = 0; $i < strlen($json); $i++) {
			if (!$comment) {
				if ($json[$i] == '{') $out .= ' array(';
				else if ($json[$i] == '}') $out .= ')';
				else if ($json[$i] == ':') $out .= '=>';
				else $out .= $json[$i];           
			} else {
				$out .= $json[$i];
			}
			if ($json[$i] == '"') $comment = !$comment;
		}
		eval($out . ';');
		return $x;
	}

	public function encode($dict) {
		return $this->_encode($dict);
    }
 
}